<template>
  <div class="password-container">
    <div class="password-card">
      <h2 class="title">修改密码</h2>
      <van-form @submit="onSubmit">
        <van-field label="编号" v-model="userForm.id" readonly> </van-field>
        <van-field label="用户" v-model="userForm.name" type="text" />

        <van-field label="原来密码" v-model="userForm.password" type="password" placeholder="请输入原密码"
          :rules="[{ pattern:regNamePwd,required: true, message: '无效密码' }]" />

        <van-field label="新的密码" v-model="userForm.password2" type="password" placeholder="请输入新密码"
          :rules="[{ pattern:regNamePwd,required: true, message: '无效密码' }]" />

        <van-field label="确认密码" v-model="userForm.password22" type="password" placeholder="请输入新密码"
          :rules="[{ pattern:regNamePwd,required: true, message: '无效密码' }]" />

        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit" class="submit-btn">
            提交修改
          </van-button>
        </div>

      </van-form>
    </div>
  </div>
</template>

<style lang="less" scoped>
.password-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f1f5f9;

  .password-card {
    width: 90%;
    max-width: 500px;
    padding: 30px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 8px 24px rgba(0,0,0,0.05);
  }

  .title {
    text-align: center;
    font-size: 22px;
    color: #1e293b;
    margin-bottom: 30px;
  }

  .van-field {
    margin-bottom: 20px;
    border-radius: 8px;
    background: #f8fafc;
    
    &::after {
      display: none;
    }

    :deep(.van-field__label) {
      color: #475569;
      width: 80px;
    }
  }

  .submit-btn {
    background: linear-gradient(45deg, #6366f1, #8b5cf6);
    border: none;
    font-weight: bold;
    margin-top: 30px;
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.95);
    }
  }
}
</style>

<script>
	import { showToast } from 'vant'
	import { updatePwdAPI } from "@/api/user.js";
	import { getUserLocal } from "@/utils/auth.js";
	export default {
		data() {
			return {
				userForm: {
					id: null,
					name: "",
					password: "",
					password2: "", //新的密码
					password22: "", //确认密码          
				},

				//规则:字母数字‘6~12        
				regNamePwd: /^[a-z0-9]{3,12}$/i,
			};
		},
		mounted() {
			let user = getUserLocal();
			this.userForm.id = user.id;
			this.userForm.name = user.name;
		},

		methods: {

			//处理提交保存
			onSubmit() {
				if (this.userForm.password2 != this.userForm.password22) {
					showToast("确认密码两次输入不一致");
					return;
				}

				//注意传递过去的参数user的属性名
				let user = this.userForm;
				delete user.password22; //删除该临时的字段
				updatePwdAPI(user).then(() => {
					showToast("密码更改成功！");
					this.$router.push({
						name: "user"
					});
				});
			},
		},
	};
</script>

<style lang="less" scoped>
</style>